import { _decorator, Component, Node, Prefab, instantiate, Vec3, tween, Collider2D, Button } from 'cc';
import { Card } from './Card';
import EventManager, { EVENT_ENUM } from './Manager/EventManager';
const { ccclass, property } = _decorator;

@ccclass('CardManager')
export class CardManager extends Component {
    @property(Prefab)
    cardPrefab: Prefab = null;

    // stock 余牌堆，tableau 接龙堆，foundation 目标堆
    @property(Node)
    stockPile: Node = null;

    private cards: Node[] = [];
    private suits: string[] = ['hearts', 'spades', 'diamonds', 'clubs'];
    private ranks: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

    start() {
        this.createCards();
        this.shuffleCards();
        this.placeCardsInStock();
    }

    createCards() {
        for (let suit of this.suits) {
            for (let rank of this.ranks) {
                let cardNode = instantiate(this.cardPrefab);
                cardNode.name = suit + "_" + rank;
                let cardComponent = cardNode.getComponent(Card);
                if (cardComponent) {
                    cardComponent.suit = suit;
                    cardComponent.rank = rank;
                    cardComponent.isFaceUp = false;
                    cardComponent.sprite.spriteFrame = cardComponent.cardBack;
                }
                this.cards.push(cardNode);
            }
        }
    }

    shuffleCards() {
        for (let i = this.cards.length - 1; i > 0; i--) {
            let j = Math.floor(Math.random() * (i + 1));
            [this.cards[i], this.cards[j]] = [this.cards[j], this.cards[i]];
        }
    }

    placeCardsInStock() {
        const offsetX = 2;
        for (let i = 0; i < this.cards.length; i++) {
            let card = this.cards[i];
            this.stockPile.addChild(card);
            card.setPosition(new Vec3(offsetX * i, 0, 0));
        }

    }

}
